package com.zhangshuo.patternDesign.singleton;

import org.junit.Test;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.SynchronousQueue;

/**
 * Created by shuo.zhang on 2017-10-17.
 */
public class SingletonTest1 {

    public boolean isLock() {
        return lock;
    }

    public void setLock(boolean lock) {
        this.lock = lock;
    }

    private volatile boolean lock;





    // 测试多线程下是否会创建多个对象，如果结果不明显，请在初始化对象的时候加一个sleep应该就看到了
    public static void main(String[] args) throws InterruptedException {

        SingletonTest1 lock = new SingletonTest1();
        Set<String> instances = Collections.synchronizedSet(new HashSet<String>());
        lock.setLock(true);


        //线程可重复使用的线程池，最大的线程大小为Integer.Max_vvv
        ExecutorService executorService = Executors.newCachedThreadPool();

        for(int i=0;i<100;i++){

            executorService.execute(() ->{
                while(true){

                    if(!lock.isLock()){
                        instances.add(BadSingleton.getInstance().toString());
                        break;
                    }
                }

            });


        }

        Thread.sleep(1000*3);

        lock.setLock(false);

        Thread.sleep(1000*3);

        executorService.shutdown();

        System.out.println("获取实例的大小为:" + instances.size());



    }


    @Test
    public void test2(){
        System.out.println(Runtime.getRuntime().availableProcessors());
        LinkedHashMap<String,String> map = new LinkedHashMap();
        map.put("C","C");
        map.put("A","A");
        Set<String> keySet = map.keySet();
        System.out.println(keySet);
    }


    @Test
    public void test3(){
        SynchronousQueue<String> queue = new SynchronousQueue<>();
        queue.add("A");
        queue.add("B");
    }

}
